package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.ExcelSubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.Map;
/*
* 以前在写controller,service层的时候，想要获取相关对象，
* 直接调用注入某个对象就好了，因为他们都交给了spring来管理
* 但是这里的监听器类不能交给spring来管理，因为这个类是需要我们手动用，
* 手动new个对象来使用它，所以不能交给spring来管理
* */
/*
* 读取excel文件的监听器
* */
public class SubjectExcelListener extends AnalysisEventListener<ExcelSubjectData>{
    /*因为这里是自己创建的监听器类，所以不能将该类注册到spring容器里面，要使用数据库接口，需要通过传参的方式传递进来*/
    private EduSubjectService subjectService;

    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    /*一行一行读取excel里面的内容*/
    @Override
    public void invoke(ExcelSubjectData data, AnalysisContext context) {
        /*1.解析从excel里面读取到的数据*/
        String oneSubjectName = data.getOneSubjectName();
        String twoSubjectName = data.getTwoSubjectName();
        /*2.判断数据库里面是否有该一级分类数据*/
        EduSubject subject = existOneSubject(subjectService, oneSubjectName);
        /*说明原先数据库里面没有这个记录*/
        if(subject==null){
            subject = new EduSubject();
            subject.setTitle(oneSubjectName);
            subjectService.save(subject);
        }
        String parentId = subject.getId();
        /*3.判断数据库里面是否有该二级分类数据*/
        subject = existTwoSubject(subjectService, twoSubjectName, parentId);
        if(subject==null){
            subject=new EduSubject();
            subject.setTitle(twoSubjectName);
            subject.setParentId(parentId);
            subjectService.save(subject);
        }
    }

    /*判断数据库里面是否有一级分类数据*/
    private EduSubject existOneSubject(EduSubjectService subjectService,String oneSubjectName){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", oneSubjectName);
        EduSubject one = subjectService.getOne(wrapper);
        return one;
    }
    /*判断数据库里面是否有二级分类数据*/
    private EduSubject existTwoSubject(EduSubjectService subjectService,String twoSubjectName,String pid){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", twoSubjectName);
        wrapper.eq("parent_id", pid);
        EduSubject one = subjectService.getOne(wrapper);
        return one;
    }

    /*在读取完excel文件之后，调用的方法*/
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }
}